﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FirmaTransportowa
{
    public partial class CashierPanelNewPackage : Form
    {
        SqlConnection conn;
        Int32 senderSelectedId;
        Int32 recipientSelectedId;
        List<Client> clientsList = new List<Client>();
        List<Recipient> recipientsList = new List<Recipient>();
        CashierPanel myParentForm;

        public CashierPanelNewPackage(CashierPanel myParent)
        {
            InitializeComponent();
            SqlConnector connection = new SqlConnector();
            conn = connection.getInstance();
            initListbox();
            this.myParentForm = myParent;            
        } 

        private bool verifyForm()
        {
            bool isFormCorrect = true;

            if (tbSenderName.Text.Trim() == String.Empty)
            {
                labelSenderNameError.Visible = true;
                isFormCorrect = false;
            }
            if (tbSenderSurname.Text.Trim() == String.Empty)
            {
                labelSenderSurnameError.Visible = true;
                isFormCorrect = false;
            }
            if (tbSenderPostcode.Text.Trim() == String.Empty)
            {
                labelSenderPostcodeError.Visible = true;
                isFormCorrect = false;
            }
            if (tbSenderCity.Text.Trim() == String.Empty)
            {
                labelSenderCityError.Visible = true;
                isFormCorrect = false;
            }
            if (tbSenderStreet.Text.Trim() == String.Empty)
            {
                labelSenderStreetError.Visible = true;
                isFormCorrect = false;
            }
            if (tbSenderHouseNumber.Text.Trim() == String.Empty)
            {
                labelSenderHouseNumberError.Visible = true;
                isFormCorrect = false;
            }
            if (tbSenderPhone.Text.Trim() == String.Empty)
            {
                labelSenderPhoneError.Visible = true;
                isFormCorrect = false;
            }
            if (tbRecipientName.Text.Trim() == String.Empty)
            {
                labelRecipientNameError.Visible = true;
                isFormCorrect = false;
            }
            if (tbRecipientSurname.Text.Trim() == String.Empty)
            {
                labelRecipientSurnameError.Visible = true;
                isFormCorrect = false;
            }
            if (tbRecipientPostcode.Text.Trim() == String.Empty)
            {
                labelRecipientPostcodeError.Visible = true;
                isFormCorrect = false;
            }
            if (tbRecipientCity.Text.Trim() == String.Empty)
            {
                labelRecipientCityError.Visible = true;
                isFormCorrect = false;
            }
            if (tbRecipientStreet.Text.Trim() == String.Empty)
            {
                labelRecipientStreetError.Visible = true;
                isFormCorrect = false;
            }
            if (tbRecipientHouseNumber.Text.Trim() == String.Empty)
            {
                labelRecipientHouseNumberError.Visible = true;
                isFormCorrect = false;
            }
            if (tbRecipientPhone.Text.Trim() == String.Empty)
            {
                labelRecipientPhoneError.Visible = true;
                isFormCorrect = false;
            }
            if (tbPackageWeight.Text.Trim() == String.Empty)
            {
                labelWightError.Visible = true;
                isFormCorrect = false;
            }

            if (isFormCorrect)
            {
                return true;
            }
            return false;

        }

        private void clearErrorsLabels()
        {
            foreach (Label label in this.Controls.OfType<Label>())
            {
                if(label.Name.Contains("Error")){
                    label.Visible=false;
                }
            }
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            clearErrorsLabels();
            if (verifyForm())
            {
                try
                {
                    conn.Open();
                    SqlCommand cmdNewClient = new SqlCommand("INSERT INTO Senders(name,surname,postcode,city,street,house_number,phone) OUTPUT INSERTED.sender_ID VALUES(" +
                        "@sname,@ssurname,@spostcode,@scity,@sstreet,@shouse_number,@sphone)", conn);
                    SqlCommand cmdNewRecipient = new SqlCommand("INSERT INTO Recipients(name,surname,postcode,city,street,house_number,phone) OUTPUT INSERTED.recipient_ID  VALUES(" +
                        "@rname,@rsurname,@rpostcode,@rcity,@rstreet,@rhouse_number,@rphone)", conn);
                    SqlCommand cmdNewPackage = new SqlCommand("INSERT INTO Package(sender_ID,recipient_ID,status,weight,add_date) VALUES(" +
                        "@sender_ID,@recipient_ID,@status,@weight,@add_date)", conn);

                    cmdNewClient.Parameters.AddWithValue("@sname", tbSenderName.Text);
                    cmdNewClient.Parameters.AddWithValue("@ssurname", tbSenderSurname.Text);
                    cmdNewClient.Parameters.AddWithValue("@spostcode", tbSenderPostcode.Text);
                    cmdNewClient.Parameters.AddWithValue("@scity", tbSenderCity.Text);
                    cmdNewClient.Parameters.AddWithValue("@sstreet", tbRecipientStreet.Text);
                    cmdNewClient.Parameters.AddWithValue("@shouse_number", tbSenderHouseNumber.Text);
                    cmdNewClient.Parameters.AddWithValue("@sphone", tbSenderPhone.Text);

                    cmdNewRecipient.Parameters.AddWithValue("@rname", tbRecipientName.Text);
                    cmdNewRecipient.Parameters.AddWithValue("@rsurname", tbRecipientSurname.Text);
                    cmdNewRecipient.Parameters.AddWithValue("@rpostcode", tbRecipientPostcode.Text);
                    cmdNewRecipient.Parameters.AddWithValue("@rcity", tbRecipientCity.Text);
                    cmdNewRecipient.Parameters.AddWithValue("@rstreet", tbRecipientStreet.Text);
                    cmdNewRecipient.Parameters.AddWithValue("@rhouse_number", tbRecipientHouseNumber.Text);
                    cmdNewRecipient.Parameters.AddWithValue("@rphone", tbRecipientPhone.Text);

                    int senderID = (int)cmdNewClient.ExecuteScalar();
                    int recipientID = (int)cmdNewRecipient.ExecuteScalar();

                    float packageWeight;
                    try
                    {
                        packageWeight = float.Parse(tbPackageWeight.Text);
                    }
                    catch
                    {
                        packageWeight = 0.0f;
                    }

                    cmdNewPackage.Parameters.AddWithValue("@sender_ID", senderID);
                    cmdNewPackage.Parameters.AddWithValue("@recipient_ID", recipientID);
                    cmdNewPackage.Parameters.AddWithValue("@status", "nowy");
                    cmdNewPackage.Parameters.AddWithValue("@weight", packageWeight);
                    cmdNewPackage.Parameters.AddWithValue("@add_date", "2005-04-04");

                    cmdNewPackage.ExecuteNonQuery();
                }
                catch (SqlException ex)
                {
                    MessageBox.Show(ex.Message, "Niepowodzenie");
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    conn.Close();
                }

                myParentForm.refreshGrid();
                this.Close();
            }
        }

        public void initListbox()
        {            
            try
            {
                conn.Open();
                SqlCommand cmdSenders = new SqlCommand("SELECT * FROM Senders", conn);
                SqlCommand cmdRecipients = new SqlCommand("SELECT * FROM Recipients", conn);

                SqlDataReader readerSenders = cmdSenders.ExecuteReader();              

                /*getting Senders Data*/
                if (readerSenders.HasRows)
                {
                    while (readerSenders.Read())
                    {
                        clientsList.Add(new Client(Int32.Parse(readerSenders["sender_ID"].ToString()), readerSenders["name"].ToString(), readerSenders["surname"].ToString(), readerSenders["postcode"].ToString(), readerSenders["city"].ToString(), readerSenders["street"].ToString(), readerSenders["house_number"].ToString(), readerSenders["phone"].ToString()));
                    }
                    listBoxSelectSender.DataSource = clientsList;
                    listBoxSelectSender.DisplayMember = "DisplayText";
                    listBoxSelectSender.ValueMember = "ReturnValue";
                    listBoxSelectSender.SelectedValueChanged += new EventHandler(listBoxSelectSender_SelectedValueChanged);
                }
                conn.Close();
                conn.Open();

                SqlDataReader readerRecipients = cmdRecipients.ExecuteReader();
                /*getting Recipients Data*/

                if (readerRecipients.HasRows)
                {
                    while (readerRecipients.Read())
                    {
                        recipientsList.Add(new Recipient(Int32.Parse(readerRecipients["recipient_ID"].ToString()), readerRecipients["name"].ToString(), readerRecipients["surname"].ToString(), readerRecipients["postcode"].ToString(), readerRecipients["city"].ToString(), readerRecipients["street"].ToString(), readerRecipients["house_number"].ToString(), readerRecipients["phone"].ToString()));
                    }
                    listBoxSelectRecipient.DataSource = recipientsList;
                    listBoxSelectRecipient.DisplayMember = "DisplayText";
                    listBoxSelectRecipient.ValueMember = "ReturnValue";
                    listBoxSelectRecipient.SelectedValueChanged += new EventHandler(listBoxSelectRecipient_SelectedValueChanged);
                }
                
                conn.Close();
            }
            catch(SqlException ex)
            {
                MessageBox.Show(ex.Message);
            }

        }


        private void listBoxSelectSender_SelectedValueChanged(object sender, EventArgs e)
        {
            if (listBoxSelectSender.SelectedIndex != -1)
            {
                senderSelectedId = Int32.Parse(listBoxSelectSender.SelectedValue.ToString());
                tbSenderName.Text = clientsList.Find(ById(senderSelectedId)).name;
                tbSenderSurname.Text = clientsList.Find(ById(senderSelectedId)).surname;
                tbSenderPostcode.Text = clientsList.Find(ById(senderSelectedId)).postcode;
                tbSenderCity.Text = clientsList.Find(ById(senderSelectedId)).city;
                tbSenderStreet.Text = clientsList.Find(ById(senderSelectedId)).street;
                tbSenderHouseNumber.Text = clientsList.Find(ById(senderSelectedId)).house_number;
                tbSenderPhone.Text = clientsList.Find(ById(senderSelectedId)).phone;
            }
        }
        private void listBoxSelectRecipient_SelectedValueChanged(object sender, EventArgs e)
        {
            if (listBoxSelectRecipient.SelectedIndex != -1)
            {
                recipientSelectedId = Int32.Parse(listBoxSelectRecipient.SelectedValue.ToString());
                tbRecipientName.Text = recipientsList.Find(ById(recipientSelectedId)).name;
                tbRecipientSurname.Text = recipientsList.Find(ById(recipientSelectedId)).surname;
                tbRecipientPostcode.Text = recipientsList.Find(ById(recipientSelectedId)).postcode;
                tbRecipientCity.Text = recipientsList.Find(ById(recipientSelectedId)).city;
                tbRecipientStreet.Text = recipientsList.Find(ById(recipientSelectedId)).street;
                tbRecipientHouseNumber.Text = recipientsList.Find(ById(recipientSelectedId)).house_number;
                tbRecipientPhone.Text = recipientsList.Find(ById(recipientSelectedId)).phone;
            }
        }

        static Predicate<Client> ById(int id)
        {
            return delegate(Client client)
            {
                return client.id==id;
            };
        }

    }
}
